package com.sl.au.controller;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.sl.au.entity.AaccountsReceivableAccorspandingContract;
import com.sl.au.entity.Account;
import com.sl.au.entity.AccountsReceivablePlan;
import com.sl.au.entity.AccountsReceivableType;
import com.sl.au.entity.Contract;
import com.sl.au.entity.ContractInfo;
import com.sl.au.entity.ContractPart;
import com.sl.au.entity.ContractPump;
import com.sl.au.entity.ContractRepair;
import com.sl.au.entity.Customer;
import com.sl.au.entity.CustomerPayInfo;
import com.sl.au.entity.InvoiceDetailInfo;
import com.sl.au.entity.InvoiceTotalInfo;
import com.sl.au.entity.InvoiceTotalInfoView;
import com.sl.au.entity.Module;
import com.sl.au.entity.User;
import com.sl.au.service.AttachmentService;
import com.sl.au.service.CustomerService;
import com.sl.au.service.EXDECustomerPayInfoService;
import com.sl.au.service.InvoiceDetailInfoService;
import com.sl.au.service.InvoiceTotalInfoService;
import com.sl.au.service.InvoiceTotalInfoViewService;
import com.sl.au.service.OperateLogService;
import com.sl.au.service.PaymentInitialService;

@RestController
@RequestMapping(value = "/ui/invoice")
public class InvoiceTotalInfoController extends BaseController {

	@Autowired
	InvoiceTotalInfoService invoiceTotalInfoService;
	@Autowired
	InvoiceTotalInfoViewService invoiceTotalInfoViewService;
	@Autowired
	OperateLogService operateLogService;
	@Autowired
	InvoiceDetailInfoService invoiceDetailInfoService;
	@Autowired
	PaymentInitialService paymentInitialService;
	@Autowired
	CustomerService customerService;
	@Autowired
	EXDECustomerPayInfoService customerPayInfoService;
	@Autowired
	AttachmentService attachmentService;

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index() {
		Module module = this.getPageModule("invoiceTotalInfo");
		ModelAndView modelAndView;
		Account a = this.getMyAccount();
		String superior = a.getUser().getSaleArea().getSuperior();
		String superiorArea = a.getUser().getSaleArea().getSuperiorArea();
		if (superiorArea.equals("外部-财务处")) {
			modelAndView = createLayoutView("invoice/invoiceindexcw");
		} else {
			modelAndView = createLayoutView("invoice/invoiceindex");
		}
		List<User> userList = paymentInitialService.getRepository().getUserList(superior);
		List<Customer> customerList = customerService.getRepository().findCustomerBySuperior(superior);
		String sInvoicePeopleId = "";
		String name = "";
		if (superior.equals("成套处")) {
			name = "潘小红";
		}
		if (superior.equals("销售处")) {
			name = "王聪";
		}
		if (name != "") {
			User aUser = paymentInitialService.getRepository().getUserName(name);
			sInvoicePeopleId = aUser.getEmpLogin().getEmpId();
		}
		modelAndView.addObject("module", module);
		modelAndView.addObject("users", userList);
		modelAndView.addObject("customers", customerList);
		modelAndView.addObject("sInvoicePeopleId", sInvoicePeopleId);
		return modelAndView;
	}

	@RequestMapping(value = "getpage", method = RequestMethod.GET)
	public Map<String, Object> getPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, String> condition = new HashMap<String, String>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		if (key == null) {
			key = "";
		}
		key = key.replaceAll("\\s+", "");
		List<InvoiceTotalInfoView> invoiceTotalInfos = invoiceTotalInfoViewService.findAllBykey1(start, length, key);
		long count = invoiceTotalInfoViewService.findAllBykeyCount1(key);
		map.put("data", invoiceTotalInfos);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	@RequestMapping(value = "getpage1", method = RequestMethod.GET)
	public Map<String, Object> getPage1(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		if (key == null) {
			key = "";
		}
		key = key.replaceAll("\\s+", "");
		List<InvoiceTotalInfoView> invoiceTotalInfos = invoiceTotalInfoViewService.findAllBykey(start, length, key);
		long count = invoiceTotalInfoViewService.findAllBykeyCount(key);
		map.put("data", invoiceTotalInfos);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	@RequestMapping(value = "getcustomerpage", method = RequestMethod.GET)
	public Map<String, Object> getcustomerpage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String customerid = request.getParameter("customerid");
		List<CustomerPayInfo> invoiceTotalInfos = customerPayInfoService.getEXDECustomerPayInfoRepository()
				.findByCustomer_Id(customerid);
		map.put("data", invoiceTotalInfos);
		return map;
	}

	@RequestMapping(value = "/updata", method = RequestMethod.POST)
	public Map<String, Object> updataPlan(@RequestBody InvoiceTotalInfo invoiceTotalInfo) {
		Map<String, Object> map = new HashMap<String, Object>();
		Account a = this.getMyAccount();
		User user = a.getUser();
		if (invoiceTotalInfo.getId() == "") {
			invoiceTotalInfo.setId(java.util.UUID.randomUUID().toString());
			invoiceTotalInfo.setCreateTime(new Date());
			invoiceTotalInfo.setUpdateTime(new Date());
			invoiceTotalInfo.setsCreateUserId(user.getEmpLogin().getEmpId());// user.getName()||getEmpId()
			// 新增开票同步生效时间
			invoiceTotalInfo.setdInvoiceEffectiveDate(new Date());
			invoiceTotalInfoService.getRepository().save(invoiceTotalInfo);
		} else {
			invoiceTotalInfo.setsCreateUserId(user.getEmpLogin().getEmpId());
			invoiceTotalInfoService.getRepository().save(invoiceTotalInfo);
		}
		// payPlanService.payNotionalPooling(accountsReceivablePlan.getsContractId(),user.getName());
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		BigDecimal bigDecimal = new BigDecimal(invoiceTotalInfo.getnInvoiceActualPrice());
		String time = null;
		// if(invoiceTotalInfo.getdInvoiceDate()!=null) time =
		// formatter.format(invoiceTotalInfo.getdInvoiceDate());
		time = formatter.format(invoiceTotalInfo.getdInvoiceDate());
		String content = "";
		content = invoiceTotalInfo.getId() == "" ? "新增"
				: "编辑" + "总开票信息【" + "发票名称:" + invoiceTotalInfo.getsInvoiceName() + ",客户名称:"
						+ invoiceTotalInfo.getsInvoiceCustomerName() + ",金额:" + bigDecimal.toString() + ",时间:" + time
						+ "】";
		operateLogService.log(user, "总开票" + invoiceTotalInfo.getId() == "" ? "新增" : "编辑", content);
		return map;
	}

	@RequestMapping(value = "/delbyid/{planIds}", method = RequestMethod.GET)
	public Map<String, Object> delbyid(@PathVariable String planIds) {
		Map<String, Object> map = new HashMap<String, Object>();
		Account a = this.getMyAccount();
		User user = a.getUser();
		String[] aplanIds = planIds.split(",");
		String ids = "";
		if (aplanIds.length > 0) {
			for (int i = 0; i < aplanIds.length; i++) {
				ids += "'" + aplanIds[i] + "',";
			}
			ids = ids.substring(0, ids.length() - 1);
		}
		List<InvoiceTotalInfo> InvoiceTotalInfoList = invoiceTotalInfoService.findByIds(ids);
		int content = 0;
		if (InvoiceTotalInfoList.size() > 0) {
			content = invoiceTotalInfoService.delete(InvoiceTotalInfoList, user);
		}
		// payPlanService.payNotionalPooling(accountsReceivablePlan.getsContractId(),user.getName());
		map.put("code", content);
		return map;
	}

	@RequestMapping(value = "/cleardate/{ids}", method = RequestMethod.GET)
	public Map<String, Object> cleardate(@PathVariable String ids) {
		Map<String, Object> map = new HashMap<String, Object>();
		Account a = this.getMyAccount();
		User user = a.getUser();
		String[] ids_ = ids.split(",");
		int content = 0;
		/*
		 * String ids_ = ""; if(aplanIds.length > 0){ for(int i = 0; i <
		 * aplanIds.length; i++){ ids_ += "'" + aplanIds[i] + "',"; } ids_ =
		 * ids.substring(0, ids.length()-1); } List<InvoiceTotalInfo>
		 * InvoiceTotalInfoList = invoiceTotalInfoService.findByIds(ids_); for
		 * (InvoiceTotalInfo invoiceTotalInfo : InvoiceTotalInfoList) {
		 * invoiceTotalInfo.setdInvoiceEffectiveDate(""); content = 1; }
		 */
		// List<InvoiceTotalInfo> InvoiceTotalInfoList = null;
		for (int i = 0; i < ids_.length; i++) {
			InvoiceTotalInfo invoiceTotalInfo = invoiceTotalInfoService.getRepository().findOne(ids_[i]);
			invoiceTotalInfo.setdInvoiceEffectiveDate(null);
			// InvoiceTotalInfoList.add(invoiceTotalInfo);
			invoiceTotalInfoService.getRepository().save(invoiceTotalInfo);
			content = 1;
		}
		map.put("code", content);
		return map;
	}

	@RequestMapping(value = "/updatedate/{ids}/{date}", method = RequestMethod.GET)
	public Map<String, Object> updatedate(@PathVariable String ids, @PathVariable Date date) {
		Map<String, Object> map = new HashMap<String, Object>();
		Account a = this.getMyAccount();
		User user = a.getUser();
		String[] ids_ = ids.split(",");
		/*
		 * Date date1 = null; date1 = formatter.parse(date);
		 */
		int content = 0;
		// List<InvoiceTotalInfo> InvoiceTotalInfoList = null;
		for (int i = 0; i < ids_.length; i++) {
			InvoiceTotalInfo invoiceTotalInfo = invoiceTotalInfoService.getRepository().findOne(ids_[i]);
			if (invoiceTotalInfo != null) {
				invoiceTotalInfo.setdInvoiceEffectiveDate(date);
				// InvoiceTotalInfoList.add(invoiceTotalInfo);
				invoiceTotalInfoService.getRepository().save(invoiceTotalInfo);
				content = 1;
			}
		}
		map.put("code", content);
		return map;
	}

	@RequestMapping(value = "import", method = RequestMethod.POST)
	public Map<String, Object> importExcel(@RequestParam("file") MultipartFile file, HttpServletRequest request,
			RedirectAttributes redirectAttributes) {

		Map<String, Object> map = new HashMap<String, Object>();

		int code = -1;
		String count = "-1";

		String saveFileName = attachmentService.upload(file);

		Account a = this.getMyAccount();
		User user = a.getUser();
		// 文件传后，再读取EXCEL写入数据库
		if (StringUtils.hasText(saveFileName)) {
			count = invoiceTotalInfoService.importExcel(saveFileName, user);
			code = 0;
		}
		String content = "";
		operateLogService.log(user, "导入开票凭据", content);
		map.put("code", code);
		map.put("count", count);
		return map;
	}

	@RequestMapping(value = "/isInitial/{id}", method = RequestMethod.GET)
	public Map<String, Object> isInitial(@PathVariable String id) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<InvoiceDetailInfo> InvoiceDetailInfos = invoiceDetailInfoService.getRepository()
				.findAllBysInvoiceTotalId(id);
		double sumScheduleSum = 0;
		if (InvoiceDetailInfos.size() > 0) {
			for (InvoiceDetailInfo invoiceDetailInfo : InvoiceDetailInfos) {
				sumScheduleSum += invoiceDetailInfo.getnInvoiceDetailPrice();
			}
		} else {
			map.put("code", 0);
		}
		map.put("code", sumScheduleSum);
		// payPlanService.payNotionalPooling(accountsReceivablePlan.getsContractId(),user.getName());
		return map;
	}
}
